/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufabc.edu.so.projetoFinal.Runner;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFileChooser;

import br.ufabc.edu.so.projetoFinal.escalonadores.Escalonador;
import br.ufabc.edu.so.projetoFinal.escalonadores.EscalonadorFCFS;
import br.ufabc.edu.so.projetoFinal.escalonadores.EscalonadorRRComPrioridade;
import br.ufabc.edu.so.projetoFinal.escalonadores.EscalonadorRRSemPrioridade;
import br.ufabc.edu.so.projetoFinal.escalonadores.EscalonadorSJFNaoPreemptivo;
import br.ufabc.edu.so.projetoFinal.escalonadores.EscalonadorSJFPreemptivo;
import br.ufabc.edu.so.projetoFinal.model.Processo;
import br.ufabc.edu.so.projetoFinal.model.ResultItem;
import br.ufabc.edu.so.projetoFinal.util.ToolsUtils;
import java.awt.Color;
import java.awt.Font;

/**
 *
 * @author davidson
 */
public class RunnerFrame extends javax.swing.JFrame {

    private String caminho;

    /**
     * Creates new form RunnerFrame
     */
    public RunnerFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton8 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Liberation Mono", 1, 15)); // NOI18N
        jLabel1.setText("Arquivo para simulação:");

        jLabel2.setFont(new java.awt.Font("Comic Sans MS", 3, 23)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 0, 7));
        jLabel2.setText("Bem Vindo ao Simulador de Escalonamento de CPU!");

        jSeparator1.setAutoscrolls(true);

        jButton1.setText("Abrir arquivo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Liberation Mono", 1, 15)); // NOI18N
        jLabel3.setText("Tipo de escalonamento:");

        jButton2.setText("FCFS");
        jButton2.setToolTipText("");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("SJF Preemptivo");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("SJF Não Preemptivo");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("RR Com Prioridade");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("RR Sem Prioridade");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton7.setText("Todos");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton8.setText("Limpar Resultado");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(188, 188, 188)
                        .add(jLabel2))
                    .add(layout.createSequentialGroup()
                        .add(45, 45, 45)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel1)
                                .add(18, 18, 18)
                                .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 464, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 121, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(org.jdesktop.layout.GroupLayout.LEADING, jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(jButton8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .add(jLabel3))
                                .add(54, 54, 54)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 636, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .add(32, 32, 32)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 962, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(31, 31, 31)
                .add(jLabel2)
                .add(28, 28, 28)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jButton1)))
                .add(30, 30, 30)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jLabel3)
                        .add(39, 39, 39)
                        .add(jButton2)
                        .add(26, 26, 26)
                        .add(jButton3)
                        .add(30, 30, 30)
                        .add(jButton4)
                        .add(29, 29, 29)
                        .add(jButton5)
                        .add(32, 32, 32)
                        .add(jButton6)
                        .add(32, 32, 32)
                        .add(jButton7)
                        .add(28, 28, 28)
                        .add(jButton8))
                    .add(layout.createSequentialGroup()
                        .add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 405, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(86, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Selecione o arquivo de simulação.");
        fileChooser.setApproveButtonText("Ok");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        caminho = "";
        int userSelection = fileChooser.showOpenDialog(null);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            caminho = fileChooser.getSelectedFile().getAbsolutePath();
        }
        this.jTextField1.setText(caminho + "/");
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        List<Escalonador> escalonadores = new ArrayList<Escalonador>();
        escalonadores.add(new EscalonadorFCFS());
        this.executeEscalonador(escalonadores);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        List<Escalonador> escalonadores = new ArrayList<Escalonador>();
        escalonadores.add(new EscalonadorSJFPreemptivo());
        this.executeEscalonador(escalonadores);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        List<Escalonador> escalonadores = new ArrayList<Escalonador>();
        escalonadores.add(new EscalonadorSJFNaoPreemptivo());
        this.executeEscalonador(escalonadores);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        List<Escalonador> escalonadores = new ArrayList<Escalonador>();
        escalonadores.add(new EscalonadorRRComPrioridade());
        this.executeEscalonador(escalonadores);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        List<Escalonador> escalonadores = new ArrayList<Escalonador>();
        escalonadores.add(new EscalonadorRRSemPrioridade());
        this.executeEscalonador(escalonadores);
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        List<Escalonador> escalonadores = new ArrayList<Escalonador>();
        escalonadores.add(new EscalonadorFCFS());
        escalonadores.add(new EscalonadorRRComPrioridade());
        escalonadores.add(new EscalonadorRRSemPrioridade());
        escalonadores.add(new EscalonadorSJFNaoPreemptivo());
        escalonadores.add(new EscalonadorSJFPreemptivo());
        this.executeEscalonador(escalonadores);
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        this.jTextArea1.setText("");
    }//GEN-LAST:event_jButton8ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RunnerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RunnerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RunnerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RunnerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RunnerFrame().setVisible(true);
            }
        });
    }

    public void executeEscalonador(List<Escalonador> escalonadores) {
        try {
            this.jLabel4.setFont(new Font("Comic Sans MS", Font.BOLD, 15));
            List<Processo> processos = ToolsUtils.getListaProcessos(jTextField1.getText());
            this.print(processos, escalonadores);
            this.jLabel4.setText("Arquivo executado com sucesso!");
            this.jLabel4.setForeground(Color.green);
        } catch (FileNotFoundException ex) {
            this.jLabel4.setText(ex.getMessage());
            this.jLabel4.setForeground(Color.red);
            Logger.getLogger(RunnerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RuntimeException ex) {
            this.jLabel4.setText(ex.getMessage());
            this.jLabel4.setForeground(Color.red);
            Logger.getLogger(RunnerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Imprime o resultado de cada execução
     *
     * @param processos
     */
    public void print(List<Processo> processos, List<Escalonador> escalonadores) {
        for (Escalonador escalonador : escalonadores) {
            List<Processo> procs = ToolsUtils.clonaLista(processos);
            ResultItem result = escalonador.execute(procs);
            this.jTextArea1.append("Escalonador: " + escalonador.getName() + "\n");
            this.printResult(result);
        }
    }

    public void printResult(ResultItem result) {
        this.jTextArea1.append("Tempo médio de espera: " + result.getTempoMedioEspera() + "\n");
        this.jTextArea1.append("Tempo médio de retorno: " + result.getTempoMedioRetorno() + "\n");
        this.jTextArea1.append("Numero de trocas de contexto: " + result.getNumeroTrocas() + "\n");
        this.jTextArea1.append("Instante   -   Processo\n");
        for (Map.Entry<String, Processo> entry : result.getDiagramaTempExex().entrySet()) {
            this.jTextArea1.append(String.format(" %s \t  %9s%d\n", entry.getKey(), "P", entry.getValue().getId()));
        }
        this.jTextArea1.append("\n");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
